// 找出树状数据中所有可展开的节点key
const getParentKeys = (data: any[]) => {
  let expandKeys: string[] = []
  const recursionTree = (data: any[]) => {
    data.forEach((item) => {
      if (item.children) {
        expandKeys = [...expandKeys, item.code]
        recursionTree(item.children)
      }
    })
  }
  recursionTree(data)
  return expandKeys
}

// 找出树状数据中所有不能展开的节点key
const getChildKeys = (data: any[]) => {
  let childKeys: string[] = []
  const recursionTree = (data: any[]) => {
    data.forEach((item) => {
      if (item.children) {
        recursionTree(item.children)
      } else {
        childKeys = [...childKeys, item.code]
      }
    })
  }
  recursionTree(data)
  return childKeys
}

// 已知某一子节点 向上获取路径
function treeFindPath(
  tree: any[],
  func: (data: any) => boolean,
  path: string[] = []
): string[] {
  if (!tree) return []
  for (const data of tree) {
    // 这里按照你的需求来存放最后返回的内容吧
    path.push(data.name)
    if (func(data)) return path
    if (data.children) {
      const findChildren = treeFindPath(data.children, func, path)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
}

/**
 * 找到树状数据中的某一个节点
 * @author liumingguo
 * @date 2022-10-20 14:15:53
 * @param tree 树状数据
 * @param func 判断函数
 * @returns
 */
//  泛型约束 保证传过来的数组可能会有children属性
const findNode = <T extends { children?: T[] }>(
  tree: T[],
  func: (nodeItem: T) => boolean
): T | null => {
  for (const node of tree) {
    if (func(node)) return node
    if (node.children) {
      const res = findNode(node.children, func)
      if (res) return res
    }
  }
  return null
}

// 将扁平数据转换成tree状数据
const getTreeData = (arr: any[]) => {
  const treeData = arr.filter((item) => {
    item.children = arr.filter((e) => {
      return item.code === e.parentCode
    })
    return !item.parentCode
  })

  return treeData
}
export { getParentKeys, getChildKeys, treeFindPath, findNode, getTreeData }
